﻿using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Autofac;
using AxLIVEXLib;
using ComputerVision.ANN;
using ComputerVision.BaseForm;
using ComputerVision.Common;
using ComputerVision.Data;
using ComputerVision.Services;
using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Drawing;
using RawInput_dll;

namespace ComputerVision
{
    public partial class frmXeVao : frmObject
    {
        private readonly RawInput _rawinput;
        private IService<ConfigrationCamera> _configCamera;
        private IService<LoaiXe> _loaiXe;
        private IService<Xe> _xe;
        private IService<VeXe> _veXe;
        private VeXe _veXe2;
        private Xe _xe2;
        //private Xe _model;

        private readonly ImageProcess _process;
        //Camera sau
        //private Capture _cap0;
        //Camera truoc
        //private Capture _cap1;
        //private int _cmr0;
        //private int _cmr1;
        //private Image<Bgr, byte> _img1;
        private Bitmap _img1End = null;
        //private Image<Bgr, byte> _img0;
        private Bitmap _img0End = null;
        //nhận diện mặt người vào
        //private Image<Bgr, byte> img3 = null;
        //nhận diện mặt người ra
        //private Image<Gray, byte> _imgGray1;
        private Image<Bgr, Byte> _biensoxevao;
        private string bienso;
        private string _computerName;
        //private string _soVe;

        private Bitmap imgT = null;
        private Bitmap imgS = null;
        private Random rand;
        private string _veXeDap;
        private string cardNumber = string.Empty;
        private bool isCardReader = false;
        private bool readOk = false;
        private bool userType = false;
        private string tempNumber = string.Empty;
        private string readerDevide = string.Empty;

        private string tempFile = string.Empty;
        private ImgageArrayVao imageArray;
        private FileUtil fileUtil;
        private int countT = 0;
        private int countS = 0;
        private string cardStatus = string.Empty;
        //private bool doInserted = false;

        private System.Text.RegularExpressions.Regex regex =
            new System.Text.RegularExpressions.Regex("\\d\\d-[A-Z][0-9A-Z]-\\d{4,5}");

        private System.Text.RegularExpressions.Regex regexoto =
            new System.Text.RegularExpressions.Regex("\\d\\d-[A-Z]-\\d{4,5}");

        public frmXeVao()
        {
            InitializeComponent();

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            _rawinput = new RawInput(Handle);
            _rawinput.CaptureOnlyIfTopMostWindow = true;    // Otherwise default behavior is to capture always
            _rawinput.AddMessageFilter();                   // Adding a message filter will cause keypresses to be handled
            _rawinput.KeyPressed += OnKeyPressed;

            _computerName = Environment.MachineName;
            _configCamera = Program.Container.Resolve<IService<ConfigrationCamera>>();
            _loaiXe = Program.Container.Resolve<IService<LoaiXe>>();
            _xe = Program.Container.Resolve<IService<Xe>>();
            _veXe = Program.Container.Resolve<IService<VeXe>>();
            _process = new ImageProcess();
            //_soVe = txtSoVe.Text;
            this.ActiveControl = txtSoVe;
            LoadLoaiXe();

            fileUtil = new FileUtil();

            axLiveTruoc.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveTruoc_OnGetPicture);
            axLiveSau.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveSau_OnGetPicture);
        }

        void axLiveSau_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countS == 1)
            {
                return;
            }
            axLiveSau.StartGrapImage(false);
            imgS = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            _img1End = imgS;
            picSau.Image = imgS;
            countS = 1;
        }

        void axLiveTruoc_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countT == 1)
            {
                return;
            }
            axLiveTruoc.StartGrapImage(false);
            imgT = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            _img0End = imgT;
            picTruoc.Image = imgT;
            countT = 1;

        }

        /// <summary>
        /// Get data from devices
        /// </summary>
        //private void CaptureWc()
        //{
        //    try
        //    {
        //        //Camera sau
        //        _cap0 = new Capture(_cmr0);
        //        _cap0.ImageGrabbed += wc0;
        //        _cap0.Start();
        //        //Camera trước
        //        _cap1 = new Capture(_cmr1);
        //        _cap1.ImageGrabbed += Wc1DetectFace;
        //        _cap1.Start();
        //    }
        //    catch (Exception)
        //    {
        //        //MessageBox.Show(ex.Message);
        //    }

        //}

        //private void Wc1DetectFace(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        var faceDetector1 = new CascadeClassifier("haarcascade_frontalface_default.xml");
        //        _img1 = _cap1.RetrieveBgrFrame();
        //        _imgGray1 = _img1.Convert<Gray, byte>();
        //        foreach (var face in faceDetector1.DetectMultiScale(_imgGray1, 1.1, 10, new Size(20, 20), Size.Empty))
        //        {
        //            _img1.Draw(face, new Bgr(Color.White), 1);
        //        }
        //        //imgVaoTruoc.Image = _img1;
        //        //picTruoc.Image = _img1.Bitmap;
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //}

        //private void wc0(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        _img0 = _cap0.RetrieveBgrFrame();
        //        ////imgVaoSau.Image = _img0;
        //        //picSau.Image = _img0.Bitmap;
        //    }
        //    catch (Exception)
        //    {

        //    }
        //}

        public void frmXeVao_Load(object sender, EventArgs e)
        {
            //CaptureWc();
            foreach (LoaiXe loaiXe in cbLoaixe.Items)
            {
                if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.XeMay.ToUpper()))
                {
                    cbLoaixe.SelectedItem = loaiXe;
                    break;
                }
            }
            Save();
            //asyCallBack = new AsyncCallback(TraningCompleted);
            //ManualReset = new ManualResetEvent(false);
            axLiveTruoc.SetToolTipX("hello");

            var item = _configCamera.ToList().ToList().FirstOrDefault(p => p.ComputerName.Contains(_computerName));
            if (item != null)
            {
                readerDevide = item.CardReader;

                this.axLiveTruoc.IpAddress = item.Server;
                this.axLiveTruoc.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveTruoc.DataPort = System.Convert.ToInt32("5550");
                this.axLiveTruoc.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveTruoc.DisablePWD = true;
                this.axLiveTruoc.DefaultCam = short.Parse(item.Cam1.ToString());
                this.axLiveTruoc.UserName = item.UserID;
                this.axLiveTruoc.Password = item.Password;
                this.axLiveTruoc.PlayX();

                this.axLiveSau.IpAddress = item.Server;
                this.axLiveSau.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveSau.DataPort = System.Convert.ToInt32("5550");
                this.axLiveSau.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveSau.DisablePWD = true;
                this.axLiveSau.DefaultCam = short.Parse(item.Cam2.ToString()); ;
                this.axLiveSau.UserName = item.UserID;
                this.axLiveSau.Password = item.Password;
                this.axLiveSau.PlayX();
            }
            else
            {
                AlertList.Warning("Bạn phải thiết lập camera và thiết bị đọc thẻ cho hệ thống trước khi sử dụng.");
            }


        }

        private void Timer_Vao_Tick(object sender, EventArgs e)
        {
            //cứ 100 mili giây đọc biển số xe vào 1 lần cho đến khi đúng định dạng biển số thì ngưng
            //Image<Bgr, Byte> myImage = new Image<Bgr, Byte>(myBitmap);
            //imgS = (Bitmap)picSau.Image;
            //imgT = (Bitmap)picTruoc.Image;
            try
            {
                _biensoxevao = new Image<Bgr, Byte>((Bitmap)picSau.Image);
            }
            catch (Exception)
            {
            }

            try
            {
                bienso = _process.docbienso(_biensoxevao, picBiensovao, neuralNetwork);
            }
            catch (Exception)
            {
            }

            //System.IO.StreamWriter file = new System.IO.StreamWriter("log.txt", true);
            //file.WriteLine(bienso);
            //file.Close();

            try
            {
                if (regex.IsMatch(bienso))
                {
                    axLiveSau.StartGrapImage(false);
                    axLiveTruoc.StartGrapImage(false);
                    Timer_Vao.Enabled = false;

                    txtBiensovao.Text = bienso;
                    foreach (LoaiXe loaiXe in cbLoaixe.Items)
                    {
                        if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.XeMay.ToUpper()))
                        {
                            cbLoaixe.SelectedItem = loaiXe;
                            break;
                        }
                    }

                    lblTrangThaiDoc.Text = Constants.StatusReading.Stopped;
                    lblTrangThaiDoc.ForeColor = Color.Red;
                    btnDocLai.Text = @"Đọc tiếp";
                    txtBiensovao.Focus();

                }
                else if (regexoto.IsMatch(bienso))
                {
                    axLiveSau.StartGrapImage(false);
                    axLiveTruoc.StartGrapImage(false);
                    Timer_Vao.Enabled = false;
                    txtBiensovao.Text = bienso;
                    foreach (LoaiXe loaiXe in cbLoaixe.Items)
                    {
                        if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.Oto.ToUpper()))
                        {
                            cbLoaixe.SelectedItem = loaiXe;
                            break;
                        }
                    }

                    lblTrangThaiDoc.Text = Constants.StatusReading.Stopped;
                    lblTrangThaiDoc.ForeColor = Color.Red;
                    btnDocLai.Text = @"Đọc tiếp";
                    txtBiensovao.Focus();
                }
                else
                {
                    _biensoxevao.Dispose();
                }
                //else
                //{
                //    //Timer_Vao.Enabled = false;
                //    txtBiensovao.Text = bienso;
                //    cbLoaixevao.SelectedText = Constants.Xe.XeDap;

                //    lblTrangThai.Text = Constants.StatusReading.Stopped;
                //    lblTrangThai.ForeColor = Color.Red;
                //    btnDocLai.Text = @"Đọc tiếp";
                //}
                //else
                //{
                //    axLiveSau.StartGrapImage(true);
                //}
            }
            catch (Exception)
            {
            }


        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Timer_Vao.Enabled == false)
            {
                axLiveSau.StartGrapImage(true);
                axLiveTruoc.StartGrapImage(true);
                countS = 0;
                countT = 0;
                Timer_Vao.Enabled = true;
                picBiensovao.Image = null;
                btnDocLai.Text = @"Ngừng";
                lblTrangThaiDoc.Text = Constants.StatusReading.Reading;
                lblTrangThaiDoc.ForeColor = Color.Blue;
            }
            else
            {
                axLiveSau.StartGrapImage(false);
                axLiveTruoc.StartGrapImage(false);
                //countS = 0;
                //countT = 0;
                Timer_Vao.Enabled = false;
                picBiensovao.Image = null;
                btnDocLai.Text = @"Đọc tiếp";
                lblTrangThaiDoc.Text = Constants.StatusReading.Stopped;
                lblTrangThaiDoc.ForeColor = Color.Red;
            }

            txtSoVe.Focus();
        }

        private void LoadLoaiXe()
        {
            var loaixe = _loaiXe.ToList().ToList();
            foreach (LoaiXe loai in loaixe)
            {
                cbLoaixe.Items.Add(loai);
            }
        }

        #region Validation

        private bool ValidCard()
        {
            _veXe = Program.Container.Resolve<IService<VeXe>>();
            _xe = Program.Container.Resolve<IService<Xe>>();

            _veXe2 = _veXe.Detail(txtSoVe.Text.Trim());
            if (txtSoVe.Text.Trim().Equals(string.Empty))
            {
                lblTrangThaiThe.Text = @"Đang chờ";
                lblTrangThaiThe.ForeColor = Color.Black;
                return false;
            }

            if (_veXe2 == null)
            {
                lblTrangThaiThe.Text = Constants.VeMessages.VeKhongCoTrongDuLieu;
                cardStatus = Constants.VeMessages.VeKhongCoTrongDuLieu;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            if (_veXe2.Status.Equals(Constants.StatusVeXe.MatVe))
            {
                lblTrangThaiThe.Text = Constants.VeMessages.MatVe;
                cardStatus = Constants.VeMessages.MatVe;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            if (_veXe2.Status.Equals(Constants.StatusVeXe.InActive))
            {
                lblTrangThaiThe.Text = Constants.VeMessages.VeKhongHoatDong;
                cardStatus = Constants.VeMessages.VeKhongHoatDong;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            _xe2 = _xe.ToList().ToList()
                            .OrderByDescending(b => b.NgayVao)
                            .FirstOrDefault(p => p.SoVe.Equals(txtSoVe.Text.Trim()));
            if (_xe2 != null && _xe2.NgayRa == null && _xe2.ImgRaTruoc == null && _xe2.ImgRaSau == null)
            {
                lblTrangThaiThe.Text = Constants.VeMessages.VeChuaRa;
                cardStatus = Constants.VeMessages.VeChuaRa;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            lblTrangThaiThe.Text = Constants.VeMessages.VeHopLe;
            lblTrangThaiThe.ForeColor = Color.Blue;

            //else
            //{
            //    lblTrangThaiThe.Text = @"";
            //}

            return true;
        }

        protected bool Validator()
        {

            if (string.IsNullOrEmpty(txtSoVe.Text))
            {
                AlertList.Error("Bạn chưa nhập số vé. Xin vui lòng kiểm tra lại");
                txtSoVe.Focus();
                return false;
            }

            int result;
            if (!int.TryParse(txtSoVe.Text, out result))
            {
                AlertList.Error("Bạn nhập số vé không hợp lệ. Xin vui lòng kiểm tra lại");
                txtSoVe.Focus();
                return false;
            }

            var soVe = _veXe.Detail(txtSoVe.Text.Trim());
            if (soVe == null)
            {
                AlertList.Error("Bạn nhập số vé không có trong dữ liệu. Xin vui lòng kiểm tra lại");
                txtSoVe.Focus();
                return false;
            }

            if (!soVe.Status.Equals(Constants.StatusVeXe.Active))
            {
                AlertList.Error("Hiện tại số vé này không hoạt động. Xin vui lòng kiểm tra lại");
                txtSoVe.Focus();

                return false;
            }

            if (cbLoaixe.SelectedItem == null)
            {
                AlertList.Error("Bạn chưa chọn loại xe. Xin vui lòng kiểm tra lại");
                cbLoaixe.Focus();
                return false;
            }

            //if (string.IsNullOrEmpty(txtBiensovao.Text))
            //{
            //    AlertList.Error("Bạn chưa nhập biển số xe. Xin vui lòng kiểm tra lại");
            //    txtBiensovao.Focus();
            //    return false;
            //}

            //if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.XeDap.ToUpper()))
            //{
            //    _img0End = imgS;
            //    _img1End = imgT;
            //}


            return true;
        }

        #endregion

        #region Insert

        protected void Insert()
        {
            try
            {
                var loaiXe = cbLoaixe.SelectedItem as LoaiXe;
                var model = new Xe
                {
                    Id = Guid.NewGuid(),
                    LoaiXeId = loaiXe.Id,
                    SoVe = txtSoVe.Text.Trim(),
                    BienSoXe = txtBiensovao.Text.ToUpper(),
                    NgayVao = DateTime.Now,
                    GiaTien = loaiXe.GiaTien,
                    ImgBienXeVao = this.imageArray.NameBienSoUrl,
                    ImgVaoTruoc = this.imageArray.NameTruocUrl,
                    ImgVaoSau = this.imageArray.NameSauUrl,
                    Status = (!userType),
                    Created = DateTime.Now,
                    CreatedBy = Constants.CurrentUser,
                    Modified = DateTime.Now,
                    ModifiedBy = Constants.CurrentUser
                };
                _xe.Create(model);

                //Reset controls
                //doInserted = true;
                cardStatus = string.Empty;
                txtSoVe.Text = string.Empty;
                txtBiensovao.Text = string.Empty;
                txtSoVe.Focus();
            }
            catch (Exception ex)
            {
                //AlertList.Error("Lỗi phát sinh khi tạo mới dữ liệu.");
                AlertList.Error(ex.ToString());
            }
        }

        #endregion

        private void btnTiep_Click(object sender, EventArgs e)
        {
            if (Validator())
            {
                this.imageArray = new ImgageArrayVao(_img0End, _img1End, (Bitmap)picBiensovao.Image, tempFile, fileUtil.tempFolderToday);
                if (fileUtil.WriteImagesVao(this.imageArray))
                {
                    Insert();
                    userType = false;
                    txtSoVe.Focus();
                }
                else
                {
                    AlertList.Error("Không ghi được ảnh chụp từ camera. Vui lòng kiểm tra lại hệ thống.");
                }
                //txtSoVe.Focus();
            }

        }

        private void timerClock_Tick(object sender, EventArgs e)
        {
            dtpGioVao.Value = DateTime.Now;
            dtpNgayvao.Value = DateTime.Now;

            //valid card
            //if (!txtSoVe.Text.Trim().Equals(string.Empty) && !txtSoVe.Text.Trim().Equals(_soVe))
            //ValidCard();
        }

        private void txtBiensovao_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            txtBiensovao.ReadOnly = false;
            txtBiensovao.SelectAll();
        }

        //Neural Network Object With Output Type String 
        private NeuralNetwork<string> neuralNetwork = null;

        //Data Members Required For Neural Network
        private Dictionary<string, double[]> TrainingSet;
        private int av_ImageHeight = 0;
        private int av_ImageWidth = 0;
        private int NumOfPatterns = 0;

        private void Save()
        {

            string[] Images = Directory.GetFiles(Application.StartupPath + @"\ImageTrainning", "*.bmp");
            NumOfPatterns = Images.Length;
            av_ImageHeight = 0;
            av_ImageWidth = 0;
            foreach (string s in Images)
            {
                var Temp = new Bitmap(s);
                av_ImageHeight += Temp.Height;
                av_ImageWidth += Temp.Width;
                Temp.Dispose();
            }
            av_ImageHeight /= NumOfPatterns;
            av_ImageWidth /= NumOfPatterns;

            int networkInput = av_ImageHeight * av_ImageWidth;
            GenerateTrainingSet();
            CreateNeuralNetwork();
        }

        private void CreateNeuralNetwork()
        {
            if (TrainingSet == null)
                throw new Exception("Unable to Create Neural Network As There is No Data to Train..");

            neuralNetwork = new NeuralNetwork<string>
                (new BP3Layer<string>(av_ImageHeight * av_ImageWidth, 295, 98, NumOfPatterns), TrainingSet);

            neuralNetwork.MaximumError = 1.1;
            neuralNetwork.LoadNetwork(Application.StartupPath + @"\ImageTrainning\Model.net");
        }

        private void GenerateTrainingSet()
        {
            // string[] Patterns = Directory.GetFiles(@"C:\Users\bienphongvnn\Desktop\hinhanhhuanluyen", "*.bmp");
            string[] Patterns = Directory.GetFiles(Application.StartupPath + @"\ImageTrainning", "*.bmp");
            TrainingSet = new Dictionary<string, double[]>(Patterns.Length);
            foreach (string s in Patterns)
            {
                var Temp = new Bitmap(s);
                TrainingSet.Add(Path.GetFileNameWithoutExtension(s),
                    ImageProcessing.ToMatrix(Temp, av_ImageHeight, av_ImageWidth));
                Temp.Dispose();
            }


        }

        private void cbLoaixe_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((LoaiXe)cbLoaixe.SelectedItem).Ten.ToUpper().Equals(Constants.Xe.XeDap.ToUpper()))
            {
                rand = new Random();
                do
                {
                    _veXeDap = rand.Next(100, 999).ToString();
                } while (_veXeDap.Equals(txtBiensovao.Text));
                //if (!string.IsNullOrEmpty(txtSoVe.Text.Trim()))
                //{
                //    txtBiensovao.Text = txtSoVe.Text.Trim().Substring(6, 4);
                //}

            }

        }

        private void frmXeVao_KeyDown(object sender, KeyEventArgs e)
        {
            if (!isCardReader)
            {
                if (e.KeyCode == Keys.F2)
                {
                    btnDocLai.PerformClick();
                }
                else if (e.KeyCode == Keys.Enter)
                {
                    if (!txtSoVe.Focused && cardStatus.Equals(string.Empty))
                    {
                        btnTiep.PerformClick();
                        //btnDocLai.PerformClick();
                        cbLoaixe.SelectedItem = cbLoaixe.Items[1];
                    }
                    else if (!txtSoVe.Focused && !cardStatus.Equals(string.Empty))
                    {
                        AlertList.Error(cardStatus);
                    }
                }
                else if (e.KeyCode == Keys.F1)
                {
                    cardNumber = string.Empty;
                    txtSoVe.Text = string.Empty;
                    txtSoVe.Focus();
                }
                else if (e.KeyCode == Keys.F3)
                {
                    cbLoaixe.SelectedItem = cbLoaixe.Items[1];
                    cbLoaixe.SelectedItem = cbLoaixe.Items[0];
                    //txtSoVe.Text = string.Empty;
                    txtBiensovao.Focus();
                }
            }
        }

        private void txtSoVe_TextChanged(object sender, EventArgs e)
        {
            //if (txtSoVe.Text.Length == 10)
            //{
            //    axLiveTruoc.OnGetPicture += axLiveTruoc_OnGetPicture;
            //    _img0End = imgT;
            //    picTruoc.Image = imgT;

            //    axLiveSau.OnGetPicture += axLiveSau_OnGetPicture;
            //    _img1End = imgS;
            //    picSau.Image = imgS;

            //    txtBiensovao.Focus();
            //    txtBiensovao.SelectAll();

            //    //Doc bien so
            //    axLiveSau.StartGrapImage(true);
            //    axLiveTruoc.StartGrapImage(true);
            //    Timer_Vao.Enabled = true;
            //    picBiensovao.Image = null;
            //    btnDocLai.Text = @"Ngừng";
            //    lblTrangThaiDoc.Text = Constants.StatusReading.Reading;
            //    lblTrangThaiDoc.ForeColor = Color.Blue;
            //}
        }

        private void txtSoVe_MouseEnter(object sender, EventArgs e)
        {
            txtSoVe.SelectAll();
        }

        private void txtSoVe_MouseDown(object sender, MouseEventArgs e)
        {
            txtSoVe.SelectAll();
        }

        private void frmXeVao_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (isCardReader)
            {
                ReadFromCardReader(e);
                if (readOk)
                {
                    axLiveSau.StartGrapImage(true);
                    countS = 0;
                    axLiveTruoc.StartGrapImage(true);
                    countT = 0;
                    //Doc bien so
                    Timer_Vao.Enabled = true;
                    btnDocLai.Text = @"Ngừng";
                    lblTrangThaiDoc.Text = Constants.StatusReading.Reading;
                    lblTrangThaiDoc.ForeColor = Color.Blue;

                    tempFile = DateTime.Now.ToString("yyyyMMddHHmmssffff");

                    txtSoVe.Text = cardNumber;
                    ValidCard();
                    //if (ValidCard())
                    //{
                    //    //var loaiXe = cbLoaixe.SelectedItem as LoaiXe;
                    //    _model = new Xe
                    //    {
                    //        Id = Guid.NewGuid(),
                    //        LoaiXeId = ((LoaiXe)cbLoaixe.SelectedItem).Id,
                    //        SoVe = txtSoVe.Text.Trim(),
                    //        BienSoXe = txtBiensovao.Text.ToUpper(),
                    //        NgayVao = DateTime.Now,
                    //        GiaTien = ((LoaiXe)cbLoaixe.SelectedItem).GiaTien,
                    //        ImgBienXeVao = this.imageArray.NameBienSoUrl,
                    //        ImgVaoTruoc = this.imageArray.NameTruocUrl,
                    //        ImgVaoSau = this.imageArray.NameSauUrl,
                    //        Status = (!userType),
                    //        Created = DateTime.Now,
                    //        CreatedBy = Constants.CurrentUser,
                    //        Modified = DateTime.Now,
                    //        ModifiedBy = Constants.CurrentUser
                    //    };
                //}
                    //axLiveTruoc.OnGetPicture += axLiveTruoc_OnGetPicture;

                    //_img0End = imgT;
                    //_img0End = (Bitmap)picTruoc.Image;

                    //axLiveSau.OnGetPicture += axLiveSau_OnGetPicture;
                    //_img1End = imgS;
                    //_img1End = (Bitmap)picSau.Image;

                    //_img1End = (Bitmap)picSau.Image;

                    //if (!txtSoVe.Text.Trim().Equals(string.Empty))
                    //{
                    //    ValidCard();
                    //    //_soVe = txtSoVe.Text.Trim();
                    //}

                    picBiensovao.Image = null;
                    txtBiensovao.Focus();
                    txtBiensovao.SelectAll();

                }
            }

        }

        private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;

            if (null == ex) return;

            // Log this error. Logging the exception doesn't correct the problem but at least now
            // you may have more insight as to why the exception is being thrown.
            //Debug.WriteLine("Unhandled Exception: " + ex.Message);
            //Debug.WriteLine("Unhandled Exception: " + ex);
            MessageBox.Show(ex.Message);
        }

        private void OnKeyPressed(object sender, InputEventArg e)
        {
            if (e.KeyPressEvent.DeviceName.Equals(readerDevide))
            {
                isCardReader = true;
                txtBiensovao.ReadOnly = true;

            }
            else
            {
                isCardReader = false;
                txtBiensovao.ReadOnly = false;
            }
        }

        private void ReadFromCardReader(KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                tempNumber = tempNumber + e.KeyChar;
                readOk = false;
                e.Handled = true;
            }
            else
            {
                cardNumber = tempNumber;
                tempNumber = string.Empty;
                readOk = true;

            }
        }

        private void frmXeVao_FormClosed(object sender, FormClosedEventArgs e)
        {
            _rawinput.KeyPressed -= OnKeyPressed;
        }

        private void txtBiensovao_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!isCardReader)
            {
                if (char.IsLetterOrDigit(e.KeyChar))
                {
                    userType = true;
                }
            }
        }


    }
}